<template>
    <div class="verify-code">
      <img 
        :src="codeUrl" 
        @click="handleClick" 
        :style="{ cursor: isDisabled ? 'not-allowed' : 'pointer' }"
        width="100"
        height="30"
        alt="验证码"
      />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
  
  const codeUrl = ref('')
  const verifyKey = ref('')
  const isDisabled = ref(false)
  const isMounted = ref(false) // 新增标志位
  
  const emit = defineEmits(['update:key'])
  
  const handleClick = () => {
    if (!isDisabled.value) {
      getVerifyCode(false)
    }
  }
  
  const getVerifyCode = async (isAutoLoad = false) => {
    if (isDisabled.value) return
    
    try {
      isDisabled.value = true
      const response = await fetch('http://localhost:8080/nerv/code', {
        method: 'GET',
        credentials: 'include'
      })
      
      const blob = await response.blob()
      if (codeUrl.value) URL.revokeObjectURL(codeUrl.value)
      codeUrl.value = URL.createObjectURL(blob)
  
      // 打印所有响应头，用于调试
      console.log('所有响应头:', response.headers)
      
      // 尝试不同的响应头名称
      const key = response.headers.get('verifyCode') || 
                 response.headers.get('verify-code') || 
                 response.headers.get('verify_code') || 
                 response.headers.get('VerifyCode')
      
      console.log('获取到的验证码key:', key)
      if (key) {
        verifyKey.value = key
        emit('update:key', key)
      } else {
        console.error('未能获取到验证码key')
        ElMessage.error('获取验证码失败，请稍后重试')
      }
  
    } catch (error) {
      if (!isAutoLoad) ElMessage.error('获取验证码失败，请稍后重试')
    } finally {
      setTimeout(() => { isDisabled.value = false }, 1500)
    }
  }
  
  onMounted(() => {
    if (!isMounted.value) { // 确保仅执行一次
      getVerifyCode(true)
      isMounted.value = true
    }
  })
  
  onUnmounted(() => {
    if (codeUrl.value) URL.revokeObjectURL(codeUrl.value)
  })
  
  // 暴露方法给父组件
  defineExpose({
    handleClick
  })
  </script>
  
  <style scoped>
  .verify-code {
    display: inline-block;
  }
  
  .verify-code img {
    vertical-align: middle;
    user-select: none;
  }
  </style> 